package net.frenopatico.citadels.view.windows;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Singleton;

import lombok.Getter;
import net.frenopatico.citadels.view.accessors.Messages;
import net.frenopatico.citadels.view.enums.OpenIdProviders;

import com.google.appengine.api.users.UserServiceFactory;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.Window;

/**
 * Window the give the user the opportunity to log in.
 *
 * @author eduardo.ramirez.ronco@gmail.com
 */
@Singleton
public class LoginWindow extends Window {
    private static final long serialVersionUID = 2831201601409318894L;

    @Getter private boolean initialized = false; // NOPMD

    /**
     * Initialize window settings.
     *
     */
    public LoginWindow() {
        super();
        this.setName( "login" );
    }

    /**
     * Wire and initialize the window.
     *
     *@param requestURI URI for the current request.
     */
    public void initialize( final String requestURI ) {
        this.removeAllComponents();

        final HorizontalLayout authInfo = new HorizontalLayout();

        this.addComponent( new Label( "Demonstrating how to do Google accounts authentication in a <a href=\"http://www.vaadin.com\">Vaadin</a> application deployed to Google App Engine.", Label.CONTENT_XHTML ) );
        this.addComponent( authInfo );

        final List<Link> links = new ArrayList<Link>( OpenIdProviders.values().length );
        final Label email = new Label( Messages.get( "user.anonymous" ) );

        for( OpenIdProviders provider : OpenIdProviders.values() ) {
            final String providerUrl = provider.getUri();
            final String loginUrl = UserServiceFactory.getUserService().createLoginURL( requestURI, null, providerUrl, Collections.<String> emptySet() );
            links.add( new Link( provider.getName(), new ExternalResource( loginUrl ) ) ); // NOPMD
        }

        email.setStyleName( "email" );
        authInfo.addComponent( email );

        for( Link link : links ) {
            authInfo.addComponent( link );
        }

        initialized = true;
    }
}
